<template>
    <div class="bigbox">
        <!-- 顶部操作栏 -->
        <!-- 第一行输入框 -->
        <el-row :gutter="12">
            <el-col :span="6">
                渠道6666666名称<el-input v-model="searchParams.channelName" style="width: 230px; margin-left: 10px;"
                    placeholder="请输入渠道名称" />
            </el-col>
            <el-col :span="6">
                渠道55状态 <el-select v-model="searchParams.status" placeholder="请选择渠道状态"
                    style="width: 229px;margin-left: 10px;" clearable>
                    <el-option v-for="item in optionsstatus" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-col>
            <el-col :span="6">
                渠道类型<el-select v-model="searchParams.type" placeholder="请选择渠道类型" style="width: 230px;margin-left: 10px;"
                    clearable>
                    <el-option v-for="item in optionstype" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-col>
        </el-row>
        <!-- 第二行输入框 -->
        <el-row :gutter="12" style="margin-top: 20px;">
            <el-col :span="6">
                <div class="block">
                    创建时间 <el-date-picker v-model="searchParams.createTime" style="width: 229px; margin-left: 6px;"
                        type="daterange" start-placeholder="开始日期" end-placeholder="结束日期"
                        :default-value="[new Date(2025, 5, 1), new Date(2025, 6, 1)]" />
                </div>
            </el-col>
            <el-col :span="6">
                <el-button :icon="Search" type="primary" @click="search">搜索</el-button>
                <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
            </el-col>
        </el-row>
        <!-- 第三行五个按钮 -->
        <el-row style="margin-top: 20px;">
            <el-col>
                <el-button :icon="Plus" plain type="primary" @click="showed">新增</el-button>
                <el-button :icon="Edit" plain type="success" @click="edit"
                    :disabled="multipleSelection.length !== 1">修改</el-button>
                <el-button :icon="Delete" plain type="danger" :disabled="multipleSelection.length == 0"
                    @click="del">删除</el-button>
                <el-button :icon="Upload" plain type="info" @click="importin">导入</el-button>
                <el-button :icon="Download" plain type="warning" @click="exported">导出</el-button>
            </el-col>
        </el-row>

        <!-- 数据表单 -->
        <el-table ref="multipleTableRef" :data="tableData" row-key="id" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" :selectable="selectable" width="55" />
            <el-table-column property="channelId" label="渠道编号" width="120" />
            <el-table-column property="channelName" label="渠道名称" width="120" />
            <el-table-column prop="type" label="渠道类型">
                <template #default="scope">
                    <el-tag type="success" v-if="scope.row.type == 1">线上渠道</el-tag>
                    <el-tag type="primary" v-if="scope.row.type == 2">线下渠道</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="渠道状态">
                <template #default="scope">
                    <el-tag type="info" v-if="scope.row.status == 0">禁用</el-tag>
                    <el-tag type="success" v-if="scope.row.status == 1">正常</el-tag>
                </template>
            </el-table-column>
            <el-table-column property="createBy" label="创建人" width="120" />
            <el-table-column property="createTime" label="创建时间" />
            <el-table-column property="remark" label="备注信息" />
            <el-table-column label="操作" class="conl">
                <template #default="scope">
                    <el-button style="border: none; color: #409EFF;" @click="edited(scope.row)" :icon="Edit" />
                    <el-button style="border: none; color: #409EFF;" @click="deled(scope.row.channelId)"
                        :icon="Delete" />
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增/修改 -->
        <el-dialog v-model="dialogVisible" :title="title" width="500">
            <el-form ref="ruleFormRef" style="max-width: 500px" :model="ruleForm" :rules="rules" label-width="auto">
                <el-form-item label="渠道名称" prop="channelName">
                    <el-input v-model="ruleForm.channelName" />
                </el-form-item>
                <el-form-item label="渠道状态" prop="status">
                    <el-radio-group v-model="ruleForm.status">
                        <el-radio v-for="(item, index) in optionsstatus" :key="index" :label="item.value">
                            {{ item.label }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="渠道类型" prop="type">
                    <el-radio-group v-model="ruleForm.type">
                        <el-radio v-for="(item, index) in optionstype" :key="index" :label="item.value">
                            {{ item.label }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="ruleForm.remark" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                        placeholder="请输入内容" />
                </el-form-item>
                <el-form-item  class="right">
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        确定
                    </el-button>
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 导入对话框 -->
        <el-dialog v-model="indialogVisible" title="用户导入" width="400" class="import">
            <div class="upload-container">
                <el-upload class="custom-upload" :action="importAction" :on-success="handleImportSuccess"
                    :on-error="handleImportError" :before-upload="beforeUpload" accept=".xls,.xlsx" multiple
                    :auto-upload="false">
                    <!-- 云图标 + 提示文字区域 -->
                    <div class="upload-drag-area">
                        <el-icon class="upload-icon"><upload-filled /></el-icon>
                        <div class="upload-text">将文件拖到此处，或 <span class="upload-link">点击上传</span></div>
                    </div>
                    <!-- 已选文件展示 -->
                    <template>
                        <div class="selected-files" v-if="fileList.length > 0">
                            <span v-for="(file, idx) in fileList" :key="idx">{{ file }} </span>
                        </div>
                    </template>
                </el-upload>
                <!-- 额外的“是否更新已存在渠道数据”复选框 -->
                <div style="text-align: center; margin-top: 10px;">
                    <el-checkbox v-model="updateExisting"
                        style="display: flex; justify-content: center;">是否更新已经存在的渠道数据</el-checkbox>
                    <span class="el-upload__tip" style="text-align: center;">
                        仅允许导入xls、xlsx格式文件。
                    </span>
                    <el-button type="text" @click="downloadTemplate" style="font-size: 12px;">下载模板</el-button>
                </div>

                <el-form-item class="right">
                    <el-button type="primary" @click="handleImport">确定</el-button>
                    <el-button @click="inresetForm">取消</el-button>
                </el-form-item>
            </div>
            <!-- 直接写的点击确定弹出提示框成功 -->
            <el-dialog v-model="innerVisible" style="width:420px; height:145px" title="导入结果" append-to-body>
                <div class="seconddia">
                    <span style="margin-top: 15px;">操作成功</span>
                    <el-form-item class="handleright">
                        <el-button type="primary" @click="handlesure">确定</el-button>
                    </el-form-item>
                </div>
            </el-dialog>
        </el-dialog>

        <!-- 页数 -->
        <div class="pagebox">
            <el-pagination v-model:current-page="pageParms.pageNum" v-model:page-size="pageParms.pageSize"
                :page-sizes="[10, 20, 30, 50]" :size="size" :disabled="disabled" background
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>

    </div>
</template>

<script setup lang="ts">
import { UploadFilled } from '@element-plus/icons-vue'
import { nextTick, onMounted, reactive, ref } from 'vue'
import {
    Search, Refresh, Plus, Edit, Delete, Upload, Download
} from '@element-plus/icons-vue'
import type { TableInstance, ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { list, add, update, detail, usrdel, exporton, exportins } from '../../../api/channel'
const total = ref(0)
const dialogVisible = ref(false)
const indialogVisible = ref(false)
const updateExisting = ref(false)
const innerVisible = ref(false)
const title = ref('')
const delId = ref('')
const multipleTableRef = ref<TableInstance>()
const downloadTemplate = () => {
    // 替换为实际模板下载地址
    window.open('https://your-domain/template.xlsx');
};
const optionsstatus = [{
    label: '禁用',
    value: 0
}, {
    label: '正常',
    value: 1
}]
const optionstype = [{
    label: '线上渠道',
    value: 1
}, {
    label: '线下渠道',
    value: 2
}]
const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
    console.log(val, "这是选中的数据");

}
onMounted(() => {
    getList()
})

const pageParms = reactive({
    pageNum: 1,
    pageSize: 10
})


interface RuleForm {
    channelId: number;
    channelName: string,
    status: number,
    type: number,
    remark: string
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    channelId: 0,
    channelName: '',
    status: 1,
    type: 1,
    remark: ''
})


const rules = reactive<FormRules<RuleForm>>({
    channelName: [
        { required: true, message: '渠道名称不能为空', trigger: 'blur' },
    ],
    status: [
        { required: true, message: '渠道状态不能为空', trigger: 'change' },
    ],
    type: [
        { required: true, message: '渠道类型不能为空', trigger: 'change' },
    ]
})


const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    dialogVisible.value = false
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))
// 导出
function exported() {
    exporton(ruleForm).then(res => {
        console.log(res, "成功")
        // 创建一个blob对象，存储excel文件数据
        let blob = new Blob([res])
        const link = document.createElement("a")
        // 创建一个下载链接，并将其赋值给href
        link.href = window.URL.createObjectURL(blob)
        link.target = "_blank"
        // 设置文件名
        let nowTime = new Date()
        link.setAttribute('download', `导出文件${nowTime.getTime()}.xlsx`)
        // 将a标签添加到页面上
        document.body.appendChild(link)
        // 触发点击事件
        link.click()
        // 移除a标签
        document.body.removeChild(link)
    })
        .catch(err => {
            console.log(err, "shibai")
        })
}

// 导入相关变量
const importAction = ref('https://your-api-domain/channel/import') // 实际导入接口地址
const fileList = ref([]) // 选中的文件列表
const importing = ref(false) // 导入加载状态

// 导入前校验文件
function beforeUpload(file: File) {
    const isExcel = file.type === 'application/vnd.ms-excel' ||
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    if (!isExcel) {
        ElMessage.error('请上传Excel文件(xls/xlsx)');
        return false;
    }
    fileList.value = [...fileList.value]; // 追加文件而非直接赋值
    return false; // 阻止自动上传
}


// 处理导入
function handleImport() {
    importing.value = true;
    const formData = new FormData();
    fileList.value.forEach(file => {
        formData.append('file', file); // 支持多文件上传
    });
    indialogVisible.value = false
    innerVisible.value = true
}

// 直接点击成功确定(但是文件不上传)
function handlesure() {
    innerVisible.value = false
}

// 导入成功回调
function handleImportSuccess(response: any, file: any, fileList: any) {
    ElMessage.success('文件上传成功，正在导入数据...');
    // 上传成功后自动触发导入处理
    handleImport();
}

// 导入失败回调
function handleImportError(error: any, file: any, fileList: any) {
    ElMessage.error('文件上传失败，请重试');
}

// 处理导入响应
function handleImportResponse(response: any) {
    if (response.code === 200) { // 假设成功状态码为200
        ElMessage.success('数据导入成功');
        // 关闭导入对话框
        indialogVisible.value = false;
        // 刷新数据
        refreshData();
    } else {
        ElMessage.error(response.message || '数据导入失败');
    }
}

// 刷新数据
function refreshData() {
    // 重置到第一页
    pageParms.pageNum = 1;
    // 调用列表接口
    getList();
}


// 导入
function importin() {
    indialogVisible.value = true
}

function inresetForm() {
    indialogVisible.value = false
}

// 新增/修改确定按钮
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (title.value === "添加渠道") {
                add(ruleForm).then(res => {
                    dialogVisible.value = false
                    getList()
                })
            } else {
                // id为是必要参数
                update(ruleForm).then(res => {
                    dialogVisible.value = false
                    getList()
                })
            }

        } else {
            console.log('error submit!', fields)
        }
    })
}

// 单个删除
function deled(channelId: number) {
    const channelIds = channelId
    ElMessageBox.confirm(
        `是否确认删除渠道编号为"${channelIds}"的数据项?`,
        '系统提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 点击确定后(必须用.then包括否则直接执行调用删除接口)，调用删除接口，传递选中的编号(传递的是channelIds不是channelId了)
        usrdel(channelIds).then(res => {
            ElMessage({
                message: '删除成功',
                type: 'success',
            });
            getList();
        }).catch(error => {
            console.error('删除失败', error);
            ElMessage({
                type: 'error',
                message: '删除失败，请重试',
            });
        });
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '删除已取消',
        });
    });
}

// 批量删除
function del() {
    // 拼接选中的渠道编号，用于提示
    const channelIds = multipleSelection.value.map(item => item.channelId).join(',');
    ElMessageBox.confirm(
        `是否确认删除渠道编号为"${channelIds}"的数据项?`,
        '系统提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 点击确定后(必须用.then包括否则直接执行调用删除接口)，调用删除接口，传递选中的编号(传递的是channelIds不是channelId了)
        usrdel(channelIds).then(res => {
            ElMessage({
                message: '删除成功',
                type: 'success',
            });
            getList();
        }).catch(error => {
            console.error('删除失败', error);
            ElMessage({
                type: 'error',
                message: '删除失败，请重试',
            });
        });
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '删除已取消',
        });
    });
}

// 在表单里打开修改提示框
function edited(row: any) {
    dialogVisible.value = true
    title.value = "修改渠道"
    detail(row.channelId).then(res => {
        // 必须传入id值否则删除时会出现更新失败
        const channelDetail = res.data;
        ruleForm.channelId = channelDetail.channelId;
        // 将选中的数据赋值给 ruleForm
        ruleForm.channelName = channelDetail.channelName
        ruleForm.status = channelDetail.status
        ruleForm.type = channelDetail.type
        ruleForm.remark = channelDetail.remark
    })
}

// 打开修改提示框
function edit(row: any) {
    if (multipleSelection.value.length === 0) return
    // 获取选中的第一条数据
    const val = multipleSelection.value[0]
    dialogVisible.value = true
    title.value = "修改渠道"
    detail(val.channelId).then(res => {
        // 必须传入id值否则删除时会出现更新失败
        const channelDetail = res.data;
        ruleForm.channelId = channelDetail.channelId;
        // 将选中的数据赋值给 ruleForm
        ruleForm.channelName = channelDetail.channelName
        ruleForm.status = channelDetail.status
        ruleForm.type = channelDetail.type
        ruleForm.remark = channelDetail.remark
    })

}

// 打开新增提示框
function showed() {
    dialogVisible.value = true
    title.value = "添加渠道"
    nextTick(() => {
        ruleFormRef.value.resetFields()
        ruleForm.remark = ''
    })
}

// 重置搜索
function resetSearch() {
    // 重置搜索参数
    searchParams.channelName = ''
    searchParams.status = null
    searchParams.type = null
    searchParams.createTime = []
    pageParms.pageNum = 1
    getList()
}

// 搜索
const searchParams = reactive({
    channelName: '',
    status: null,
    type: null,
    createTime: []
})
const tableData: any = ref([])

// 页数
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    pageParms.pageNum = 1
    pageParms.pageSize = val
    getList()
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    pageParms.pageNum = val
    getList()
}

// 搜索
function search() {
    pageParms.pageNum = 1
    getList()
}

// 列表
function getList() {
    // 合并分页参数和搜索参数(如果直接传入pageParms传入不了搜索内容 导致搜索内容为全部 定义一个新的参数和页数一并传入)
    const params = {
        ...pageParms,
        ...searchParams
    }
    // 调接口传入参数
    list(params).then(res => {
        console.log(res, "获取列表数据")
        tableData.value = res.rows
        total.value = res.total
    }).catch(error => {
        console.error('获取列表失败', error)
    })
}

const multipleSelection = ref<User[]>([])
interface User {
    id: number
    date: string
    name: string
    address: string
}
</script>

<style scoped>
.bigbox {
    padding: 20px;
    color: var(--el-text-color-regular);
    font-size: var(--el-form-label-font-size);
    /* font-weight: 700; */
}

.demo-date-picker {
    display: flex;
    width: 100%;
    padding: 0;
    flex-wrap: wrap;
}

.demo-date-picker .block {
    padding: 30px 0;
    text-align: center;
    border-right: solid 1px var(--el-border-color);
    flex: 1;
}

.demo-date-picker .block:last-child {
    border-right: none;
}

.demo-date-picker .demonstration {
    display: block;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin-bottom: 20px;
}

:deep(.el-dialog__body) {
    padding: 2px 20px;
}

/* 自定义上传区域样式 */
.custom-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    text-align: center;
    padding: 20px;
    height: 180px;
    margin-top: 28px;
    cursor: pointer;
    transition: border-color 0.3s;

}

.custom-upload:hover {
    border-color: #409eff;
}

/* 云图标 + 文字区域 */
.upload-drag-area {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.upload-icon {
    font-size: 67px;
    color: #c0c4cc;
    margin-top: 25px;
    margin-bottom: 10px;
}

.upload-text {
    color: #999;
}

.upload-link {
    color: #409eff;
    cursor: pointer;
}

:deep(.el-form-item--default .el-form-item__content) {
    /* display: flex; */
    /* margin-top: 25px; */
    line-height: 32px;
    /* justify-content: flex-end; */
}

/* 已选文件展示（可选） */
.selected-files {
    margin-top: 10px;
    color: #666;
}

:deep(.el-checkbox__label) {
    font-size: 12px;
}

.seconddia {
    margin-top: -30px;
}

/* 页数 */
.pagebox {
    display: flex;
    margin-top: 38px;
    justify-content: flex-end;
}

:deep(.el-dialog__body) {
    padding-left: 45px;
}

:deep(.import .el-dialog__body) {
    padding-left: 20px;
}

:deep(.import .right) {
    display: flex;
    justify-content: flex-end;
}

:deep(.el-form-item__content) {
    /* margin-top: 15px;
    display: flex;
    justify-content: flex-end; */
}

:deep(.dialog-footer) {
    display: flex;
    justify-content: flex-end;
}
</style>